using System.Text.RegularExpressions;

namespace RSCore;

/// <summary>
/// 将tModLoader的Key与RS的KeyData相互转换
/// </summary>
public abstract class KeyConverter
{
	/// <summary>
	/// 当前版本的实例
	/// </summary>
	public static KeyConverter Instance { get; set; } = new KeyConverter144();

	/// <summary>
	/// 将tModLoader的Key转换为RS的KeyData
	/// </summary>
	/// <param name="key"> </param>
	/// <returns> </returns>
	public abstract KeyData Convert(string key);

	/// <summary>
	/// 将RS的KeyData转换为tModLoader的Key
	/// </summary>
	/// <param name="key"> </param>
	/// <returns> </returns>
	public abstract string Convert(KeyData key);

	private static readonly Regex _matchNoPrefix = new(@"^(.*?)\.(.*?)(?:\.(.*?))?(?:\..*)?$", RegexOptions.Compiled);

	public static string Normalize(string key)
	{
		if (key.StartsWith("Mods", StringComparison.Ordinal))
		{
			return key[(key.IndexOf('.', "Mods.".Length) + 1)..];
		}
		else
		{
			return key;
		}
	}

	/// <summary>
	/// 拆分Key，并去除Mods前缀
	/// </summary>
	/// <param name="key"> </param>
	/// <returns> </returns>
	protected static Match SplitKey(string key)
	{
		Debug.Assert(!key.StartsWith("Mods."));
		return _matchNoPrefix.Match(key);
	}
}